#!/usr/bin/env python
# coding: utf-8

import os
import re
import shutil
import zipfile
import time
import datetime
import string
from onshs.ne.tnxxx.tnxxxcfg_basecase import *


log_node_prefix = "Check_systemclock"
log_node_fail = log_node_prefix+r"_fail"
log_node_ne = log_node_prefix+r"_success"
log_node_success = log_node_prefix
log_node_summary = log_node_prefix +r"_summary"

log_file_notexisted_fail = "the file:%s isn't existed\n"
log_file_connect_fail = "connect ip:%s failed"
log_cpld_fail = "connect ip:%s %d %s OPCA %d failed" #eg: connect ip:%s slotid CM48E16 opcaslotid failed
log_node_ne_Log = "Check_systemclock ne:%s success\n" #每次都记此LOG在 ‘log_node_ne’
log_node_success_successLog = "ip:%s Check_systemclock success\n" #success记这个在  ‘log_node_success’
log_node_success_failLog = "Check_systemclock ne:%s failed\n"     #fail记这个在 ‘log_node_success’


class TestCase(TnxxxCfg_BaseCase):
    """
    TestCase
    """
    OPTIONS = [        
        {
            'opt' : '--cfgfile',
            'dest': 'cfgfile',
            'metavar' : 'CFGFILE',
            'help' : 'the file of ip list configuration',
            'required' : False,
            'default' : "ip.txt"
        },
        {
            'opt' : '--path',
            'dest': 'path',
            'metavar' : 'PATH',
            'help' : 'the directory of 705upgrade',
            'required' : False,
            'default' : "D:\heavysmoker\workspace\suites\info_collect"
        }
    ]
    
        #初始化信息
    def info_init(self):
        self.info_dic = {}  

        return True
    
    #得到IPLIST
    def get_iplist(self):
        iplist_filted = []                
        if os.path.isfile(os.getcwd()+r'/'+ self.iplistfile):
            iplist = open(os.getcwd()+r'/'+ self.iplistfile)            
        else:
            self.info_show(log_node_fail, log_file_notexisted_fail%(self.iplistfile))            
            return iplist_filted 
        
        for line in iplist:
            if re.match(r'^\s*$', line) is not None : continue # 忽略空白行
            if re.match(r'^\s*#', line) is not None : continue # 忽略注释行            
            iplist_filted.append(line.strip('\n'))        
            
        iplist.close()
        
        return iplist_filted
    
    #跟LOG相关函数
    def info_show(self, node, info):
        if not self.info_dic.has_key(node):
            self.info_dic[node] = ""
        self.info_dic[node] += info + '\n'
        return True

    def info_file_clear(self):
        if os.path.exists(self.work_path+r'/common_log'):
            shutil.rmtree(self.work_path+r'/common_log')
        
        return True    
    
    def info_file_save(self):
        path = self.work_path+'//'
        
        for node in self.info_dic:
            info_list = open(path+node+'_'+self.worktime+'.txt','a')            
            info_list.write(self.info_dic[node])
            info_list.close()
        return True
    
    def getCLIPass(self):
        #3333端口下得到CLI pass
        passList = []

        cmd = r'''$.dbgcli.0.Cmd "queryasyn valid 1, UsrInfo, (Psw), Name='root'"'''
        rtn_str = self.tnxxx.send_rtn_str(cmd, self.get_ne_ip(0), 0, MTN_PORT)
        if rtn_str=='':
            self.info_show(log_node_fail, log_file_connect_fail%(self.get_ne_ip(0)))
            self.info_show(log_node_summary, "Check systemclock ip:%s failed"%self.get_ne_ip(0))            
            return passList 
        #得到pass
        #passList = re.findall(r"result:\nPsw\n{\r\n  \"(\w+)\"\r\n}\n", rtn_str, 0)
        passList = re.findall(r"result:\nPsw\n{\r\n  \"(.+)\"\r\n}\n", rtn_str, 0)
        return passList[0]
        
    def getMasterPPC(self):
        slotList = []
        cmd = r'''$.dbgcli.0.Cmd "queryasyn valid 1, NeStat, (MasterPPC), *"'''
        rtn_str = self.tnxxx.send_rtn_str(cmd, self.get_ne_ip(0), 0, MTN_PORT)
        if rtn_str == '':
            self.info_show(log_node_fail, log_file_connect_fail%(self.get_ne_ip(0)))
            self.info_show(log_node_summary, "Check systemclock ip:%s failed"%self.get_ne_ip(0))            
            return slotList 
        slotList = re.findall(r"{\r\n  (\d)\r\n}", rtn_str, 0)
        
        return (int)(slotList[0])

    def getCardList(self):
        card_info_list = []
        self.tnxxx.connect(self.get_ne_ip(0),0,CLI_PORT,"root",self.cliPass)
        rtn = self.tnxxx.send_rtn_str("show card", self.get_ne_ip(0), 0, CLI_PORT)
        if rtn == '':
            self.info_show(log_node_fail, log_file_connect_fail%(self.get_ne_ip(0)))
            self.info_show(log_node_summary, "Check systemclock ip:%s failed"%self.get_ne_ip(0))
            return card_info_list 
        card_info_list = re.findall(r"slot:\s+(\d+)\s+(?:--More--\s+)?stat:\s+\w+\s+(?:--More--\s+)?Card:\s+(\w+)\s+", rtn, re.I)
        return card_info_list
            
    def checkCM48E16CLK(self,slotId):
        
        rtn = self.tnxxx.send_rtn_str("d 0xa%d080000+0x56*4,1,4"%slotId,self.get_ne_ip(0), self.masterPPCSlot, DEV_PORT)
        cpldValue1 = (re.findall(r"150:                    000000(\w+ |\d+)", rtn, re.I))[0]
        rtn = self.tnxxx.send_rtn_str("d 0xa%d080000+0x58*4,1,4"%slotId,self.get_ne_ip(0), self.masterPPCSlot, DEV_PORT)
        cpldValue2 = (re.findall(r"160:  000000(\w+ |\d+)", rtn, re.I))[0]
        
        cpldValue1 = int(cpldValue1,16)
        cpldValue2 = int(cpldValue2,16)
        
        #0x56:bit0,bit1==0 and 0x58:bit0 select ppc==master ppc(为1表示来自交叉板一；为0表示来自交叉板二)
        if (cpldValue1&0x03==0x0 and self.masterPPCSlot==3 and cpldValue2==0x1) or (cpldValue1&0x03==0x0 and self.masterPPCSlot==4 and cpldValue2==0x0):
            return True
        else:
            return False
   
        
    def checkN64F01CLK(self,slotId):
        cmd = "d 0xa2000000+0x41*4,1,4"
        rtn = self.tnxxx.send_rtn_str(cmd, self.get_ne_ip(0), slotId, DEV_PORT)
        cpldValue1 = (re.findall(r"100:           0000000(\w+|\d+)", rtn, re.I))[0]
        cpldValue1 = int(cpldValue1,16)
        
        cmd2 = "d 0xa2000000+0x44*4,1,4"
        rtn = self.tnxxx.send_rtn_str(cmd2, self.get_ne_ip(0), slotId, DEV_PORT)
        cpldValue2 = (re.findall(r"110:  0000000(\w+|\d+)", rtn, re.I))[0]
        cpldValue2 = int(cpldValue2,16)
        
        if (cpldValue1&0x03==0x0 and (( cpldValue2&0x04==0x4 and self.masterPPCSlot==3) or (cpldValue2&0x04==0x0 and self.masterPPCSlot==4 )) ): 
            return True
        else:
            return False
        
    def _execute(self):
        self.work_path = self.options.path
        self.info_init()
        
        worktime = str(datetime.datetime.now())
        self.worktime = worktime[:4]+worktime[5:7]+worktime[8:10]+'_'+worktime[11:13]+worktime[14:16]+worktime[17:19]
        self.iplistfile = self.options.cfgfile
        
        self.info_show(log_node_ne, "The operation begin time %s \n"%(self.worktime))
        
        ip_list = self.get_iplist()         
   
        for ip in ip_list:
            self.set_ne_ip(0, ip)
            #得到CLI下root的pass
            self.cliPass = self.getCLIPass()
            if self.cliPass == []:
                continue
            #得到主用PPC槽位号
            self.masterPPCSlot = self.getMasterPPC()
            if self.masterPPCSlot==[]:
                continue 
            #得到所有槽位号
            card_info_list = self.getCardList()
            if card_info_list == []:
                continue
            
            checkSuccess=True;
            for card_info in card_info_list:
                slot = int(card_info[0])
                #if slot not in slot_list : continue
                card_name = card_info[1].upper() #转化为大写，dic中的都是大写
                if card_name=="CM48E16":
                    if self.checkCM48E16CLK(slot):
                        print "cm48e16 success"
                    else:
                        checkSuccess=False
                        print "cm48e16 fail"
                        self.info_show(log_node_fail, log_cpld_fail%(ip,slot,card_name,self.masterPPCSlot) )
                        self.info_show(log_node_summary, "Systemclock check ip:%s failed"%ip)
                        break
                          
                elif card_name=="N64F01" or card_name=="N16F01":
                    if self.checkN64F01CLK(slot):
                        print "n64f01(n16f01) success"
                    else:
                        checkSuccess=False
                        print "n64f01(n16f01) fail"
                        self.info_show(log_node_fail, log_cpld_fail%(ip,slot,card_name,self.masterPPCSlot) )
                        self.info_show(log_node_summary, "Systemclock check ip:%s failed"%ip)
                        break
            
            if checkSuccess:
                print "Sucess In ip: %s\n" % ip
                self.info_show(log_node_success, log_node_success_successLog%(ip))
            else:
                print "Fail In ip: %s\n" % ip
                self.info_show(log_node_success, log_node_success_failLog%(ip))
            self.info_show(log_node_ne, log_node_ne_Log%(ip))
            
        worktime = str(datetime.datetime.now())
        self.worktime_end = worktime[:4]+worktime[5:7]+worktime[8:10]+'_'+worktime[11:13]+worktime[14:16]+worktime[17:19]
        
        self.info_show(log_node_ne, "The operation end time %s "%(self.worktime_end))

        self.info_file_save() 
        return True
    
if __name__ == "__main__" :
    case = TestCase()
    case.execute()